package com.rulin.asp.attachment.controller;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.javatuples.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.rulin.asp.attachment.entity.Attachment;
import com.rulin.asp.attachment.service.AttachService;

@Controller
@RequestMapping("/attachment")
public class AttachmentController {
	
	@Autowired
	private AttachService attachService;

	@RequestMapping(value = "/uploadByBoxId", method = RequestMethod.POST)
	public List<Attachment> uploadPic(HttpServletRequest request,HttpServletResponse response) throws FileNotFoundException, IOException{
			String areaId = (String) request.getParameter("areaId");
			MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
			List<Pair<String, InputStream>> files = pickOutFileNameAndStream(mRequest);
			List<Attachment> list = attachService.uploadPic(files,areaId);
			return list;
			
//			String address = attachService.uploadPic(files,areaId);
//			String baseUrl = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();
//			String url = baseUrl+"/attachment/download.jspa?address="+address+"&isinline=true";
//			jsonBean.setResults(url);
//			jsonBean.setMessage("success");
	}

	/**
	 * 获取附件名和附件流
	 * @param mRequest
	 * @return
	 * @throws IOException
	 */
	private List<Pair<String, InputStream>> pickOutFileNameAndStream(MultipartHttpServletRequest mRequest) throws IOException{
		List<Pair<String, InputStream>> files = new ArrayList<Pair<String, InputStream>>();
		for (Map.Entry<String, MultipartFile> entry :  mRequest.getFileMap().entrySet()) {
			 MultipartFile file = entry.getValue();
			 files.add(Pair.with(file.getOriginalFilename(), file.getInputStream()));
		}
		return files;
	}
	
	/**
	 * 下载或显示附件
	 * @param address
	 * @param isinline
	 * @param response
	 * @throws IOException 
	 */
	@RequestMapping(value = "/download.json", method = RequestMethod.GET)
	public void download(String address, boolean isinline, HttpServletResponse response) throws IOException{
		Attachment attachment = attachService.getAttachment(address);
		if(attachment != null){
			
			response.reset();
			response.setContentType(getContextType(attachment.getFileName()));
			response.setHeader("Content-disposition", getDisposition(attachment.getFileName(), isinline));
			response.setHeader("Content-Length", String.valueOf(attachment.getFileSize()));
			
			attachService.exportToOutputStream(address,response.getOutputStream());
		}else{
			throw new IllegalArgumentException(String.format("附件(%s)不存在", address));
		}
	}
	
	private static String getContextType(String filename) {
		String extension = FilenameUtils.getExtension(filename).toLowerCase();
		String context = contextMap.get(extension);
		
		if (context != null) {
			return context + "; charset=utf-8";
		}
		else {
			return "application/octet-stream; charset=utf-8";
		}
	}
	
	private static Map<String, String> contextMap = new HashMap<String, String>();
	
	static {
		contextMap.put("xls", "application/-excel");
		contextMap.put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
		contextMap.put("doc", "application/vnd.msword");
		contextMap.put("docx", "application/octet-stream");
		contextMap.put("ppt", "applications/-powerpoint");
	}
	
	/**
	 * 判断附件是展示还是下载
	 * @param filename
	 * @param isinline
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	protected static String getDisposition(String filename, boolean isinline) throws UnsupportedEncodingException {
		if (isinline) {
			return "inline; filename=" + URLEncoder.encode(filename, "UTF-8");
		}
		else {
			return "attachment; filename=" + URLEncoder.encode(filename, "UTF-8");
		}
	}
	
	@RequestMapping(value = "/getAttachmentsByBoxId.json", method = RequestMethod.GET)
	public List<Attachment> getAttachments(String areaId){
		List<Attachment> list = attachService.getAttachments(areaId);
		return list;
	}
	
	@RequestMapping(value = "/deleteAttachment.json", method = RequestMethod.POST)
	public void deleteAttachment(String attachmentId){
		attachService.deleteAttachmentById(attachmentId);
	}
}
